package com.zhidisoft.crm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zhidisoft.crm.entity.SysFunction;
import com.zhidisoft.crm.entity.SysUser;
import com.zhidisoft.crm.service.ISysFunctionService;
import com.zhidisoft.crm.service.ISysUserService;
import com.zhidisoft.crm.vo.AjaxVo;

@Controller	
public class LoginController extends BaseController {
	
	@Autowired
	private ISysUserService service;
	
	@Autowired
	private ISysFunctionService funcService;
	
	
	/**
	 * 进入登陆界面
	 * @return
	 */
	@GetMapping("/login")
	public ModelAndView login(String servletPath) {
		return new ModelAndView("login.html","servletPath",servletPath);
	}
	
	/**
	 *2,登陆按钮
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody	
	public AjaxVo login(SysUser sysUser){
		if (sysUser == null) 
			return new AjaxVo().setErrorCode("1001").setErrorMsg("用户名或密码不能为空！");
		if (StringUtils.isEmpty(sysUser.getUsername())||StringUtils.isEmpty(sysUser.getPassword())) 
			return new AjaxVo().setErrorCode("1001").setErrorMsg("用户名或密码不能为空！");
		
		SysUser dbUser = service.findByUserName(sysUser.getUsername());
		if (dbUser == null) 
			return new AjaxVo().setErrorCode("1002").setErrorMsg("用户名不存在！");
		StandardPasswordEncoder spe = new StandardPasswordEncoder();//获取spring加密对象
		if (!spe.matches(sysUser.getPassword(), dbUser.getPassword())) 
			return new AjaxVo().setErrorCode("1002").setErrorMsg("密码输入有误！");
		List<SysFunction> functions = null;
		if (dbUser.getIs_admin() != null && dbUser.getIs_admin().intValue() == 1){
			//所有菜单列表 
			functions = funcService.findFuncAll();
		}else {
			//functions = funcService.findByUser(getCurUser());
			functions = funcService.findByUser(dbUser.getId());
		}
		setSessionAttr("funcList", functions);
		setSessionAttr("userId", dbUser.getId());
		return new AjaxVo().setErrorCode("0");
	}
}
